// utils/request.js
// import getBaseUrl from './baseUrl'

// 基础配置
// const BASE_URL = 'http://localhost:8080'
const BASE_URL="https://www.bigpigbig.cn/stage-api"
const BASE_URL_File = 'http://localhost:8080'
const TIMEOUT = 15000; // 超时时间（毫秒）
import {wxlogin} from './tokenUtil'
// 请求拦截器（发送请求前处理）
const requestInterceptor = (config) => {
  wx.showLoading({
    title: '加载中...',
    mask: true // 显示透明蒙层，防止触摸穿透
  });
  
  // 自动携带 Token
  const token = wx.getStorageSync('token');
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}` // 根据后端要求修改 Token 字段
    };
  }
  return config;
};

// 响应拦截器（接收响应后处理）
const responseInterceptor = (response) => {
  wx.hideLoading();
  const { statusCode, data } = response;
  
  // 未授权处理（401）
  if (data && data.code === 401) {
    wxlogin()
    wx.reLaunch({
      url: '/pages/mine/login/login'
    })
    return Promise.reject(new Error('未授权，请重新登录'));
  }
  
  // 状态码非 200 视为错误
  if (statusCode !== 200) {
    console.log('网络错误:', response);
    wxlogin()
    wx.showToast({ title: data.msg || '网络错误', icon: 'error' });
    return Promise.reject(new Error(`网络错误: ${statusCode}`));
  }
  
  // 业务逻辑错误处理
  if (data.code !== 200) {
    wx.showToast({ title: data.msg || '请求失败', icon: 'error' });
    wxlogin()
    return Promise.reject(data);
  }

  return data; // 返回核心数据
};

// 封装核心请求方法
const request = (method, url, data = {}, config = {}) => {
  // 合并配置
  const mergedConfig = requestInterceptor({
    url: `${BASE_URL}${url}`,
    method: method.toUpperCase(),
    data: data,
    timeout: TIMEOUT,
    ...config
  });

  return new Promise((resolve, reject) => {
    wx.request({
      ...mergedConfig,
      success: (res) => {
        try {
          const processedData = responseInterceptor(res);
          resolve(processedData);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({ title: '网络连接失败', icon: 'none' });
        reject(err);
      }
    });
  });
};

// 封装常用方法
export const http = {
  get: (url, params = {}, config = {}) => request('GET', url, params, config),
  post: (url, data = {}, config = {}) => request('POST', url, data, config),
  put: (url, data = {}, config = {}) => request('PUT', url, data, config),
  delete: (url, data = {}, config = {}) => request('DELETE', url, data, config),
  upload: (url, filePath, formData = {}, config = {}) => {
    return new Promise((resolve, reject) => {
      wx.showLoading();
      
      wx.uploadFile({
        url: `${BASE_URL_File}${url}`,
        filePath: filePath,
        name: 'file', // 根据后端要求修改字段名
        formData: formData,
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
              resolve(data);
            } catch (error) {
              reject(new Error('解析响应数据失败'));
            }
          } else {
            reject(new Error(`上传失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          console.error('上传失败:', err);
          wx.showToast({ title: '上传失败', icon: 'none' });
          reject(err);
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    });
  }
};